package com.ja.openchat.ui.me;

import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.text.format.DateUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;

import com.bigkoo.pickerview.builder.TimePickerBuilder;
import com.bigkoo.pickerview.listener.CustomListener;
import com.bigkoo.pickerview.listener.OnTimeSelectChangeListener;
import com.bigkoo.pickerview.listener.OnTimeSelectListener;
import com.bigkoo.pickerview.view.TimePickerView;
import com.blankj.utilcode.util.BarUtils;
import com.google.gson.JsonObject;
import com.ja.openchat.BR;
import com.ja.openchat.R;
import com.ja.openchat.databinding.FragmentPersonalDataBinding;
import com.ja.openchat.ui.chat.group.ModifyFieldActivity;
import com.ja.openchat.viewmodels.PersonalDataViewModel;
import com.ja.openchat.views.AttachCopyPopupView;
import com.ja.openchat.views.ChooseListDialog;
import com.ja.openchat.views.CustomDatePickerDialogFragment;
import com.ja.openchat.views.ModifyNickNameDialog;
import com.ja.openchat.views.OnChooseListListener;
import com.lljjcoder.bean.CityBean;
import com.lljjcoder.bean.ProvinceBean;
import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.enums.PopupPosition;
import com.sahooz.library.Country;
import com.zy.openchat.core.manager.TelegramManager;
import com.zy.openchat.core.manager.TgResponse;
import com.zy.openchat.core.manager.TgResultBlock;
import com.zy.openchat.core.model.config.AppConfigInfo;
import com.zy.openchat.core.model.user.UserInfo;
import com.zy.openchat.core.model.user.UserMyInfo;
import com.zy.openchat.util.MediaUtils;

import org.apache.commons.lang3.StringUtils;
import org.joda.time.DateTimeUtils;

import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;

import me.goldze.mvvmhabit.base.BaseFragment;
import me.goldze.mvvmhabit.utils.ToastUtils;

//编辑个人资料
public class PersonalDataFragment extends BaseFragment<FragmentPersonalDataBinding, PersonalDataViewModel> implements CustomDatePickerDialogFragment.OnSelectedDateListener {

    private TimePickerView pvTime;

    @Override
    public int initContentView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return R.layout.fragment_personal_data;
    }

    @Override
    public int initVariableId() {
        return BR.viewModel;
    }
    public List<String> chooseLables = new ArrayList<>();
    @Override
    public void initView() {
        super.initView();
        BarUtils.setStatusBarColor(getActivity(), getResources().getColor(R.color.color_f7f7f7));
        chooseLables.clear();
        chooseLables.add(getString(R.string.man_text));
        chooseLables.add(getString(R.string.woman_text));
        binding.titleBar.setOnRightListener(v -> viewModel.finish());

        AppConfigInfo configInfo = AppConfigInfo.getAppWithoutLoginConfigInfo();

        if(configInfo!=null){
            if(!configInfo.can_see_qr_code){
                binding.myQrcodeBtn.setVisibility(View.GONE);
            }
        }

        initTimePicker();
    }

    @Override
    public void initViewObservable() {
        super.initViewObservable();
        viewModel.mUC.getSelectPic().observe(this, unused -> {
            MediaUtils.choosePhotoFg(this, true);
        });
        viewModel.mUC.getType().observe(this, integer -> {
            switch (integer) {
                case 1:
                    //设置昵称
//                    ModifyFieldActivity.start_setMyNickname(getActivity());
                    modifyNickName();
                    break;
                case 2:
                    //设置用户名
                    ModifyFieldActivity.start_setMyUsername(getActivity());
                    break;
                case 3:
                    ModifyFieldActivity.start_setMySignature(getActivity(), viewModel.userSignature.get());
                    break;
            }
        });
        viewModel.mUC.getShowPaymentPasswordDialogEvent().observe(this, maps -> {
            String content = (String) maps.get("content");
            if (!TextUtils.isEmpty(content)) {
                int type = (int) maps.get("type");
                View view = binding.tvNick;
                switch (type) {
                    case 1:
                        view = binding.tvNick;
                        break;
                    case 2:
                        view = binding.tvName;
                        break;
                    case 3:
                        view = binding.tvPhone;
                        break;
                }
                new XPopup.Builder(getActivity()).hasShadowBg(false).atView(view).popupPosition(PopupPosition.Top).asCustom(new AttachCopyPopupView(getActivity(), content)).show();
            }
        });
        binding.birthBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                CustomDatePickerDialogFragment.showDatePickDialog(getChildFragmentManager(),PersonalDataFragment.this);
                pvTime.show();
            }
        });
        binding.genderBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ChooseListDialog.showChooseListDialog(getContext(), chooseLables,userMyInfo==null?0:userMyInfo.gender , new OnChooseListListener() {
                    @Override
                    public void onChoose(int position, String value) {
                        if(userMyInfo!=null){
                            editUerInfoEx(position,userMyInfo.birth,userMyInfo.country,userMyInfo.countryCode,userMyInfo.province,userMyInfo.city,userMyInfo.cityCode);
                        }
                    }
                });
            }
        });
        loadUserInfoEx();
    }

    private void editUerInfoEx(int gender,String birth,String country,String countryCode,String province,String city,String cityCode){
        showDialog();
        final UserMyInfo myInfo = new UserMyInfo(gender,birth,country,countryCode,province,city,cityCode);
        TelegramManager.getTelegramManager().setUserInfoExt(getContext(), myInfo, new TgResultBlock<TgResponse>() {
            @Override
            public void onResult(Map<String, Object> request, JsonObject response, TgResponse obj) {
                dismissDialog();
                if(obj==null||!obj.ok){
                    ToastUtils.showShort(getString(R.string.request_error));
                }else{
                    userMyInfo = myInfo;
                    setUserInfoUi();
                }
            }

            @Override
            public void onTimeout(Map<String, Object> request) {
                dismissDialog();
                ToastUtils.showShort(getString(R.string.request_error));
            }
        });
    }

    private void setUserInfoUi(){
        if(userMyInfo==null){
            return;
        }
        binding.genderText.setText(getString(userMyInfo.gender==0?R.string.man_text:R.string.woman_text));
        binding.birthText.setText(userMyInfo.birth);
        viewModel.setCountry(userMyInfo);
        setCurrentDate();
    }

    private UserMyInfo userMyInfo = null;

    private void loadUserInfoEx(){
        TelegramManager.getTelegramManager().getUserInfoEx(getContext(), new TgResultBlock<UserMyInfo>() {
            @Override
            public void onResult(Map<String, Object> request, JsonObject response, UserMyInfo obj) {
                userMyInfo = obj;
                setUserInfoUi();
            }

            @Override
            public void onTimeout(Map<String, Object> request) {

            }
        });
    }

    @Override
    public void onSelectedDate(int year, int monthOfYear, int dayOfMonth) {
        String birth = String.format("%d-%s-%s",year,formatTime(monthOfYear+1),formatTime(dayOfMonth));
        if(userMyInfo!=null){
            editUerInfoEx(userMyInfo.gender,birth,userMyInfo.country,userMyInfo.countryCode,userMyInfo.province,userMyInfo.city,userMyInfo.cityCode);
        }
    }

    private String formatTime(int time){
        if(time>=10){
            return String.valueOf(time);
        }else{
            return String.format("0%d",time);
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        viewModel.loadFullInfo();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1 && data != null) {
            String country = data.getStringExtra("country");
            Country countryInfo = Country.fromJson(country);
            String city = "";
            String province = "";
            String cityCode = "";
            if(countryInfo.code == 86){
                ProvinceBean provinceBean = data.getParcelableExtra("province");
                CityBean cityBean = data.getParcelableExtra("city");
                province = provinceBean.getName();
                city = cityBean.getName();
                cityCode = cityBean.getId();
            }

            if(userMyInfo!=null){
                editUerInfoEx(userMyInfo.gender,userMyInfo.birth,countryInfo.name,String.valueOf(countryInfo.code),province,city,cityCode);
            }
        } else {
            List<String> photos = MediaUtils.getResultAlbumData(getActivity(), requestCode, resultCode, data);
            if (photos != null && photos.size() > 0) {
                viewModel.changeMyPhoto(photos.get(0));
            }
        }
    }


    private void modifyNickName(){
        ModifyNickNameDialog dialog = new ModifyNickNameDialog(getContext(), UserInfo.getUserInfo().displayName(), new ModifyNickNameDialog.OnButtonClickListener() {
            @Override
            public void onClick(String nickname, ModifyNickNameDialog dialog) {
                saveMyNickName(nickname,dialog);

            }
        });
        new XPopup.Builder(getContext()).asCustom(dialog).show();
    }

    private void saveMyNickName(String nickName,ModifyNickNameDialog dialog) {
        if (!StringUtils.isEmpty(nickName)) {
            showDialog();
            TelegramManager.getTelegramManager().setMyNickName(getActivity(), nickName, new TgResultBlock<TgResponse>() {
                @Override
                public void onResult(Map<String, Object> request, JsonObject response, TgResponse obj) {
                    dismissDialog();
                    if (obj.ok) {//设置成功
                        ToastUtils.showShort(getString(R.string.modified_successfully_text));
                        dialog.dismiss();
                    } else {
                        ToastUtils.showShort(getString(R.string.request_error) + obj.errString);
                    }
                }

                @Override
                public void onTimeout(Map<String, Object> request) {
                    dismissDialog();
                    ToastUtils.showShort(getString(R.string.request_error));
                }
            });
        } else {
            ToastUtils.showShort(getString(R.string.firstname_null_hint));
        }
    }


    private void initTimePicker() {//Dialog 模式下，在底部弹出

        pvTime = new TimePickerBuilder(getContext(), new OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date, View v) {
//                Toast.makeText(getContext(), getTime(date), Toast.LENGTH_SHORT).show();
                Log.i("pvTime", "onTimeSelect");
                String birth = getTime(date);
                if(userMyInfo!=null){
                    editUerInfoEx(userMyInfo.gender,birth,userMyInfo.country,userMyInfo.countryCode,userMyInfo.province,userMyInfo.city,userMyInfo.cityCode);
                }
                pvTime.dismiss();
            }
        })
                .setTimeSelectChangeListener(new OnTimeSelectChangeListener() {
                    @Override
                    public void onTimeSelectChanged(Date date) {
                        Log.i("pvTime", "onTimeSelectChanged");
                    }
                })
                .setLayoutRes(R.layout.pickerview_time_date, new CustomListener() {

                    @Override
                    public void customLayout(View v) {
                        TextView tv_commit = (TextView) v.findViewById(R.id.tv_commit);
                        TextView tv_cancel = (TextView) v.findViewById(R.id.tv_cancel);
                        tv_commit.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                pvTime.returnData();
                                /*pvTime.dismiss();*/
                            }
                        });
                        tv_cancel.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                pvTime.dismiss();
                            }
                        });
                    }
                })
                .setType(new boolean[]{true, true, true, false, false, false})
                .isDialog(true) //默认设置false ，内部实现将DecorView 作为它的父控件。
                .addOnCancelClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        Log.i("pvTime", "onCancelClickListener");
                    }
                })
                .setItemVisibleCount(3) //若设置偶数，实际值会加1（比如设置6，则最大可见条目为7）
                .setLineSpacingMultiplier(2.0f)
                .isAlphaGradient(true)
                .build();

        Dialog mDialog = pvTime.getDialog();
        if (mDialog != null) {

            FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(
                    ViewGroup.LayoutParams.MATCH_PARENT,
                    ViewGroup.LayoutParams.WRAP_CONTENT,
                    Gravity.BOTTOM);

            params.leftMargin = 0;
            params.rightMargin = 0;
            pvTime.getDialogContainerLayout().setLayoutParams(params);

            Window dialogWindow = mDialog.getWindow();
            if (dialogWindow != null) {
                dialogWindow.setWindowAnimations(com.bigkoo.pickerview.R.style.picker_view_slide_anim);//修改动画样式
                dialogWindow.setGravity(Gravity.BOTTOM);//改成Bottom,底部显示
                dialogWindow.setDimAmount(0.3f);
            }
        }
    }

    private void setCurrentDate(){
        Calendar curDate = Calendar.getInstance();
        if(userMyInfo != null && !TextUtils.isEmpty(userMyInfo.birth)){
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
            ParsePosition parsePosition = new ParsePosition(0);
            Date date = format.parse(userMyInfo.birth,parsePosition);
            curDate.setTime(date);
            pvTime.setDate(curDate);
        }
    }

    private String getTime(Date date) {//可根据需要自行截取数据显示
        Log.d("getTime()", "choice date millis: " + date.getTime());
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        return format.format(date);
    }
}